const fs = require("node:fs");
const path = require("node:path");

const userMapper = require("../mapper/userMapper.js");

function add(entity) {
    return new Promise((resolve, reject) => { 
        if (!entity.username || !entity.password || !entity.secretKey) {
            reject("parameter error")
            return;
        }
       
        userMapper.addUser(entity, (err) => {
            if (err) { reject(err); return; }
            resolve()
        })
    })  
}

function get() {
    return new Promise((resolve, reject) => { 
        userMapper.getUser((err, result) => {
            if (err) { reject(err); return; }
            resolve(result)
        })
    })  
}

function update(entity) {
    return new Promise((resolve, reject) => { 
        if (!entity.secretKey) {
            reject("parameter error")
            return;
        }

        userMapper.getUser((err, result) => {
            if (err) { reject(err); return; }
            if (!result) {
                userMapper.addUser(entity, (err) => {
                    if (err) { reject(err); return; }
                    resolve()
                })
            } else {
                userMapper.updateUser(entity, (err) => {
                    if (err) { reject(err); return; }
                    resolve()
                })
            }
        })
    })  
}

function saveUser() { 
    return new Promise((resolve, reject) => {
        userMapper.getUser((err, entity) => {
            if (err) { reject(err); return }
       
            var writer = fs.createWriteStream(path.join(__dirname, "../../core/static/js2/user.js"));
            writer.write("var _user = ");
            writer.write(JSON.stringify(entity));
            writer.end(';');
    
            resolve()
        })
    })
}

function updateAndSaveUser(user){
    return new Promise((resolve, reject) => {
        update(user).then(() => {
            saveUser().then(() => {
                resolve()
            }).catch(e => {
                reject(e)
            })
        }).catch(e => {
            reject(e)
        })
    })
}

exports.add = add
exports.get = get
exports.update = update
exports.saveUser = saveUser
exports.updateAndSaveUser = updateAndSaveUser